package dao

import (
	"context"
	"fmt"
	"time"

	"webx/config"

	"github.com/go-redis/redis/v8"
)

var (
	rdb *redis.Client
	ctx = context.Background()
)

func InitRedis() error {
	cfg := config.GetConfig().Redis

	rdb = redis.NewClient(&redis.Options{
		Addr:     fmt.Sprintf("%s:%d", cfg.Host, cfg.Port),
		Password: cfg.Password,
		DB:       cfg.DB,
		PoolSize: cfg.PoolSize,
	})

	_, err := rdb.Ping(ctx).Result()
	if err != nil {
		return fmt.Errorf("failed to connect redis: %v", err)
	}

	return nil
}

func GetRedis() *redis.Client {
	return rdb
}

func CloseRedis() error {
	return rdb.Close()
}

func SetCache(key string, value interface{}, expiration time.Duration) error {
	return rdb.Set(ctx, key, value, expiration).Err()
}

func GetCache(key string) (string, error) {
	return rdb.Get(ctx, key).Result()
}

func DelCache(key string) error {
	return rdb.Del(ctx, key).Err()
}
